package com.fy.proj5_permission_transaction_cache.service.impl;

import com.fy.proj5_permission_transaction_cache.mapper.UserMapper;
import com.fy.proj5_permission_transaction_cache.mapper.UserRoleMapper;
import com.fy.proj5_permission_transaction_cache.model.User;
import com.fy.proj5_permission_transaction_cache.model.UserRole;
import com.fy.proj5_permission_transaction_cache.service.CacheService;
import com.fy.proj5_permission_transaction_cache.service.RoleService;
import com.fy.proj5_permission_transaction_cache.model.Role;
import com.fy.proj5_permission_transaction_cache.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Autowired
    private CacheService cacheService;
    
    @Autowired
    private RoleService roleService;

    @Override
    // 暂时移除缓存，确保获取最新数据
    // @Cacheable(value = "users", key = "'allUsers'")
    public List<User> findAllUsers() {
        List<User> users = userMapper.findAll();
        // 为每个用户加载角色信息，并为每个角色加载权限信息
        for (User user : users) {
            User userWithRoles = userMapper.findUserWithRoles(user.getId());
            if (userWithRoles != null && userWithRoles.getRoles() != null) {
                for (Role role : userWithRoles.getRoles()) {
                    // 为每个角色加载权限信息
                    Role roleWithPermissions = roleService.findRoleWithPermissions(role.getId());
                    if (roleWithPermissions != null) {
                        role.setPermissions(roleWithPermissions.getPermissions());
                    }
                }
                user.setRoles(userWithRoles.getRoles());
            }
        }
        return users;
    }

    @Override
    @Cacheable(value = "users", key = "#id")
    public User findUserById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public User findUserByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    @Transactional
    @CacheEvict(value = "users", key = "'allUsers'")
    public boolean addUser(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        int result = userMapper.insert(user);
        if (result > 0) {
            // 缓存新增用户信息
            cacheService.set("user:" + user.getId(), user, 1, TimeUnit.HOURS);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    @Caching(
        put = @CachePut(value = "users", key = "#user.id"),
        evict = @CacheEvict(value = "users", key = "'allUsers'")
    )
    public boolean updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        int result = userMapper.update(user);
        if (result > 0) {
            // 更新缓存
            cacheService.set("user:" + user.getId(), user, 1, TimeUnit.HOURS);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    @CacheEvict(value = "users", allEntries = true)
    public boolean deleteUser(Long id) {
        // 先删除用户角色关联
        userRoleMapper.deleteByUserId(id);
        // 再删除用户
        int result = userMapper.deleteById(id);
        if (result > 0) {
            // 删除缓存
            cacheService.delete("user:" + id);
            return true;
        }
        return false;
    }

    @Override
    public List<User> findUsersByPage(int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        return userMapper.findByPage(offset, pageSize);
    }
    
    @Override
    public List<User> findUsersByPageAndSearch(int page, int pageSize, String search) {
        int offset = (page - 1) * pageSize;
        return userMapper.findByPageAndSearch(offset, pageSize, search);
    }

    @Override
    public int getUserCount() {
        return userMapper.countUsers();
    }
    
    @Override
    public int getUserCountBySearch(String search) {
        return userMapper.countUsersBySearch(search);
    }

    @Override
    @Transactional
    @CacheEvict(value = {"users", "roles"}, allEntries = true)
    public boolean assignRolesToUser(Long userId, List<Long> roleIds) {
        // 先删除该用户原有的角色关联
        userRoleMapper.deleteByUserId(userId);
        
        // 批量插入新的角色关联
        if (roleIds != null && !roleIds.isEmpty()) {
            List<UserRole> userRoles = new ArrayList<>();
            for (Long roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoles.add(userRole);
            }
            userRoleMapper.batchInsert(userRoles);
        }
        
        // 清除用户缓存
        cacheService.delete("user:" + userId);
        return true;
    }

    @Override
    // 暂时移除缓存，确保获取最新数据
    // @Cacheable(value = "users", key = "'userWithRoles:' + #userId")
    public User findUserWithRoles(Long userId) {
        return userMapper.findUserWithRoles(userId);
    }
}